<template>
    <tableLayout :columns="columns" :get="getData" :params="params"
        :row-selection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange, onSelect: onSelectItemChange, type: 'radio' }"
        ref="layout">

        <template #button>
            <a-button type="primary" style="margin-left: 20px" @click="taskHandle">办理</a-button>
            <a-button type="primary" style="margin-left: 20px" @click="flowProcess">进度</a-button>
            <a-button type="primary" style="margin-left: 20px" @click="testHandle">测试</a-button>
        </template>

        <template #operationMore="item">
            <div class="editable-row-operations">
                <span>
                    <a @click="taskHandle(null, item.value.record)">办理</a>
                </span>
                <span>
                    <a @click="flowProcess(null, item.value.record)">进度</a>
                </span>

            </div>
        </template>

    </tableLayout>
    <Modal ref="flowViewerModal" :editItem="flowItem" style="top:0;bottom:0;"></Modal>
    <HandleTask v-model:visible="isModalVisible" :taskDefinitionKey="taskDefinitionKey"
        :processInstanceId="processInstanceId" :businessKey="businessKey" :taskInfo="taskInfo" @cancel="handleCancel" />
    <TaskSubmitModal v-model:visible="taskSubmitVisible" :task-id="taskInfo?.Id" :task-info="taskInfo" @success="handleTaskSubmitSuccess"
        @cancel="handleTaskSubmitCancel" />
</template>

<script lang="ts" setup>
import tableLayout from '@/components/tableLayout/tableLayout.vue';
import { defineComponent, ref, onMounted, onBeforeMount } from 'vue';
import { notification, message } from 'ant-design-vue';
import { mapState, useStore } from 'vuex';
import { getData, completeTask, returnTo, getNextNodeInfo, jumpTask } from '@/api/flowToDo';
import Modal from '../../components/flowViewer/flowViewer.vue';
import HandleTask from '../workbenches/handleTask.vue';
// 在script部分添加导入
import TaskSubmitModal from '@/components/sys/TaskSubmitModal.vue';

let store = useStore();
const layout = ref();
const columns = [
    { title: '主键', dataIndex: 'Id' },
    { title: '名称', dataIndex: 'Name' },
    { title: '创建时间', dataIndex: 'CreatedDate' },
]

let params = ref();
const flowViewerModal = ref();
const taskDefinitionKey = ref();
const processInstanceId = ref();
const flowItem = ref({});
const taskInfo = ref({});
const businessKey = ref();
// 任务提交模态框显隐状态
const taskSubmitVisible = ref(false);
// 模态框显隐状态
const isModalVisible = ref(false);
const taskHandle = (event: any, record: any) => {
    if (record)
        selectedItem.value = record;
    if (!selectedItem.value) {
        message.warning('请选择一条数据');
        return;
    }
    taskDefinitionKey.value = selectedItem.value.TaskDefinitionKey;

    isModalVisible.value = true;
    processInstanceId.value = selectedItem.value.ProcessInstanceId;
    businessKey.value = selectedItem.value.BusinessKey;
    taskInfo.value = selectedItem.value;
}

// 修改completeTaskClick方法
const completeTaskClick = () => {
  // 打开自定义的任务提交模态框，而不是直接提交
  taskSubmitVisible.value = true;
};

// 添加任务提交成功和取消的处理方法
const handleTaskSubmitSuccess = () => {
    // 处理成功逻辑
    taskSubmitVisible.value = false;
    layout.value.getData(); // 刷新任务列表
};

const handleTaskSubmitCancel = () => {
  // 处理取消逻辑
  taskSubmitVisible.value = false;
};

const flowProcess = (event: any, record: any) => {
    if (record)
        selectedItem.value = record;
   
    if (selectedItem.value) {   
        flowViewerModal.value.open();
        flowItem.value = selectedItem.value;
    }
}

onBeforeMount(() => {
    params.value = { InvolvedUser: store.state.user.user_id };
});

//多选
const selectedRowKeys = ref<any[]>([]);
const selectedItem = ref();
const onSelectChange = (keys: []) => {
    selectedRowKeys.value = keys;
}

const onSelectItemChange = (record: {}, selected: any) => {
    selectedItem.value = record;
}

const handleCancel = () => {
    isModalVisible.value = false;
    layout.value.getData();
};

const testHandle = async (event: any, record: any) => {
    if (record)
        selectedItem.value = record;
    console.log(selectedItem);
    if (!selectedItem.value) {
        message.warning('请选择一条数据');
        return;
    }
    taskSubmitVisible.value = true;
    // getNextNodeInfo({
    //     taskId: selectedItem.value.Id
    // }).then((res) => {
    //     console.log(res);
    // }).catch((err) => {
    //     notification.error({
    //         message: '错误',
    //         description: '请求失败:' + err,
    //     });
    // });

     try {
        // 先设置taskInfo，确保TaskSubmitModal能正确获取任务ID
        taskInfo.value = selectedItem.value;
        
        // 获取下一个节点信息
        const res = await getNextNodeInfo({
            taskId: selectedItem.value.Id
        });
        
        console.log('下一个节点信息:', res);
        
        if (res.data && res.data.Code === 1 && res.data.Data) {
            // 标准化节点数据格式
            const nodesData = Array.isArray(res.data.Data) ? res.data.Data : [res.data.Data];
            
            // 检查所有节点是否都有用户
            let hasUsers = true;
            for (const node of nodesData) {
                // 如果节点没有预设办理人且没有候选用户，则需要用户选择
                if (!node.Assignee && (!node.CandidateUsers || node.CandidateUsers.length === 0)) {
                    hasUsers = false;
                    break;
                }
            }
            
            // if (hasUsers) {
            //     // 所有节点都有用户，直接提交任务
            //     const completeRes = await completeTask({
            //         TaskId: selectedItem.value.Id,
            //         Comment: '测试自动提交'
            //     });
                
            //     if (completeRes.data && completeRes.data.Code === 1 && completeRes.data.Data === true) {
            //         message.success('任务提交成功');
            //         layout.value.getData(); // 刷新任务列表
            //     } else {
            //         throw new Error(completeRes.data?.Message || '任务提交失败');
            //     }
            // } else {
                // 有节点没有用户，弹出选择页面
                taskSubmitVisible.value = true;
            //}
        } else {
            throw new Error(res.data?.Message || '获取下一个节点信息失败');
        }
    } catch (err: any) {
        console.error('处理失败:', err);
        notification.error({
            message: '错误',
            description: '处理失败:' + (err.message || err),
        });
    }
}
</script>

<style lang="scss" scoped>
.editable-row-operations a {
    margin-right: 8px;
}
</style>